package com.loiot.baqi.service.job;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.loiot.baqi.commons.message.email.EmailClient;
import com.loiot.baqi.commons.message.email.SimpleEmailVo;
import com.loiot.baqi.constant.ApplicationConst;
import com.loiot.baqi.dao.ZpCompanyJobInfoDao;
import com.loiot.baqi.pojo.TaskScheduleHeartbeat;
import com.loiot.baqi.service.TaskScheduleHeartbeatService;
import com.loiot.baqi.status.HeartbeatJobType;
import com.loiot.baqi.status.HeartbeatResultType;
import com.loiot.commons.utils.DateUtil;
import com.loiot.commons.utils.StringUtil;

 
public abstract class JobTaskDefine {

	
	@Resource
	private TaskScheduleHeartbeatService taskScheduleHeartbeatService;//定时心跳
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	protected EmailClient emailClient;

	public abstract void doTask();
	
	public int resultCode=HeartbeatResultType.SUCCESS.getCode();
	public String exceptionContent;
	public Integer jobType;
	
	public void addHeartbeat(){
		TaskScheduleHeartbeat hardBeat= new TaskScheduleHeartbeat();
		if(!StringUtil.isBlank(this.exceptionContent)){
			resultCode=HeartbeatResultType.ERROR.getCode();
			hardBeat.setExceptionContent(exceptionContent);
		}
		hardBeat.setInDate(new Date());
		hardBeat.setResultType(resultCode);
		hardBeat.setJobType(jobType);
		
		try {
			taskScheduleHeartbeatService.addTaskScheduleHeartbeat(hardBeat);
			//如果有异常 则 发送邮件通知
			if(this.resultCode==HeartbeatResultType.ERROR.getCode()){
				this.sendEmail();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			log.info("已添加心跳");
		}
	}
	
	public void sendEmail() throws InterruptedException{
			 SimpleEmailVo vo = new SimpleEmailVo();
			 vo.addEmail("273035735@qq.com");
             vo.setTitle("憬仪定时bug");
             vo.setContent(HeartbeatJobType.get(this.jobType).getTitle()+"发现异常\n<br>"+this.exceptionContent);
             emailClient.send(vo);
			 Thread.sleep(10000);
             log.info("发送时间："+DateUtil.toString(DateUtil.getNow(), DateUtil.DEFAULT_LONG_FORMAT));
		 }

}
